// 初始化admin账号脚本
// 用于解决admin登录失败的问题

const AdminModel = require('./model/admin_model.js');
const timeUtil = require('../framework/utils/time_util.js');

/**
 * 初始化admin账号
 */
async function initAdminAccount() {
    try {
        console.log('开始初始化admin账号...');
        
        // 检查是否已存在admin账号
        const existingAdmin = await AdminModel.getOne({}, 'ADMIN_ID,ADMIN_NAME,ADMIN_STATUS');
        
        if (existingAdmin) {
            console.log('admin账号已存在:', existingAdmin);
            
            // 如果admin状态不是启用，则更新状态
            if (existingAdmin.ADMIN_STATUS !== 1) {
                console.log('更新admin账号状态为启用...');
                await AdminModel.edit(
                    { ADMIN_ID: existingAdmin.ADMIN_ID },
                    { ADMIN_STATUS: 1 }
                );
                console.log('admin账号状态已更新为启用');
            }
            
            return {
                success: true,
                message: 'admin账号已存在且状态正常',
                adminId: existingAdmin.ADMIN_ID
            };
        }
        
        // 创建新的admin账号
        console.log('创建新的admin账号...');
        const adminData = {
            ADMIN_NAME: 'admin',
            ADMIN_PHONE: '13900000000',
            ADMIN_STATUS: 1, // 启用状态
            ADMIN_TYPE: 1,   // 超级管理员
            ADMIN_LOGIN_CNT: 0,
            ADMIN_LOGIN_TIME: 0,
            ADMIN_TOKEN: '',
            ADMIN_TOKEN_TIME: 0,
            ADMIN_ADD_TIME: timeUtil.time(),
            ADMIN_EDIT_TIME: timeUtil.time(),
            
            // 新增：用户关联字段
            linkedUserId: '', // 初始为空，需要手动关联
            linkedStoreIds: [], // 关联的门店ID列表
            permissions: {
                device_management: true,
                store_management: true,
                user_management: true,
                order_management: true,
                payment_management: true,
                statistics: true,
                system_settings: true
            },
            lastLoginDevice: '',
            isActive: true,
            role: 'super_admin',
            description: '超级管理员账号'
        };
        
        const result = await AdminModel.insert(adminData);
        
        console.log('admin账号创建成功:', result);
        
        return {
            success: true,
            message: 'admin账号创建成功',
            adminId: result.id
        };
        
    } catch (error) {
        console.error('初始化admin账号失败:', error);
        return {
            success: false,
            message: '初始化admin账号失败: ' + error.message
        };
    }
}

module.exports = {
    initAdminAccount
};
